<template>
  <div class='order-detail'>
    <div class="order_status">
      <div v-if="order.order_status==4" class="top_status" style="color: #F9C254;">
        <van-icon name="clock-o" />
        <span class="status">{{status[order.order_status]}}</span>
      </div>
      <div v-else class="top_status" style="color: #fb2b2c;">
        <van-icon name="clock-o" />
        <span class="status">{{status[order.order_status]}}</span>
      </div>
    </div>

    <van-cell-group class="address" inset>
      <van-cell title-class="address_detail" :title="`${order.p_c_a}${order.r_address}`">
        <template #label>
          <div class="name">
            <span>{{order.receive_name}}</span>
            <span>{{order.r_phone}}</span>
          </div>
        </template>
      </van-cell>
    </van-cell-group>

    <!-- <van-cell-group class="logistics" inset v-if="order.order_status>2">
      <van-cell title="物流信息">
        <template #label>
          <div class="tracking_number">
            <span @click="copyTrackingNumber">运单号：{{order.tracking_number}}</span>
            <van-icon :name="require('@/assets/img/my/copy.png')" @click="copyTrackingNumber" />
          </div>
        </template>
      </van-cell>
    </van-cell-group> -->

    <van-cell-group class="products" :border="false" inset>
      <div v-for="(item, index) in product" :key="index">
        <van-cell class="shopurl" :title="item.shopinfo.shop_name" :icon="`${resourceURL}${item.shopinfo.imagesurl}`" :border="false" is-link center @click="shopDetail(item.shop_id)" />
        <van-card class="product" v-for="(items, indexs) in item.detailinfo" :key="indexs" :num="items.quantity" :desc="items.p_s_name" :title="items.product_name" :thumb="`${resourceURL}${items.cover_url}`" @click.stop="$router.replace({
              path:'./product',
              query:{
               id:items.product_id
              }
            })">
          <template #price>
            <div v-if="order.order_type==1">￥{{items.sale_price}}</div>
            <div v-if="order.order_type==2">{{items.growth_coin}}积分</div>
          </template>
          <!-- <template #footer>
            <div class="one_option_btn">

            </div>
          </template> -->
        </van-card>
      </div>
      <div class="option_btn">
        <van-button size="small" plain round v-if="order.order_status==2||order.order_status==2||order.order_status==3" @click="aftersale(order.order_id,product[0].detailinfo[0].detail_id)">退款</van-button>
        <van-button size="small" plain round v-if="order.order_status==4" @click="aftersale(order.order_id,product[0].detailinfo[0].detail_id)">申请售后</van-button>
        <van-button v-if="order.is_comment==0&&order.order_status==4" type="primary" class="btn" size="small" plain round @click="comments(order.order_id,product[0].detailinfo[0].detail_id)">评价</van-button>
        <van-button size="small" class="btn" v-if="order.order_status==4&&order.is_comment==1" plain round @click="onAddCartClicked(product)">再次购买</van-button>
        <van-button v-if="order.order_status==1" size="small" class="btn" plain round @click="cancelOrder">取消订单</van-button>
        <van-button v-if="order.order_status==2" type="primary" class="btn" size="small" plain round @click="remindDelivery">提醒发货</van-button>
        <van-button v-if="order.order_status==3" size="small" plain round @click="logistics(order.order_id)">查看物流</van-button>
        <!-- <van-button v-if="order.order_status==10||order.order_status==7||order.order_status==6" size="small" plain round @click="goCustomerService">联系客服</van-button> -->

        <van-button v-if="order.order_status==3" type="primary" class="btn" size="small" plain round @click="confirmReceive">确认收货</van-button>
      </div>
    </van-cell-group>

    <van-cell-group class="total" :border="false" inset v-if="!(order.order_status==6||order.order_status==7||order.order_status==10)">
      <van-cell title="商品总价" :value="order.order_type==1?`￥${order.products_amount}`:`${order.points}积分`" value-class="not_showy" :border="false" />
      <van-cell title="运费" :border="false">
        <template #default>
          <div v-if="order.express_fee>0">￥{{order.express_fee}}</div>
          <div v-else class="coupon_showy">免运费</div>
        </template>
      </van-cell>
      <!--order_type: 订单类型 1购买普通商品 2兑换商品 3爱心餐 4团餐 5线下商品 -->
      <van-cell title="消费券" :border="false" v-if="order.order_type==1">
        <template #default>
          <div v-if="order.coupon_amount>0">-￥{{order.coupon_amount}}</div>
          <div v-else class="coupon_showy">未使用消费券</div>
        </template>
      </van-cell>
      <van-cell title="实付款" :value="`￥${order.pay_amount}`" value-class="showy" :border="false" v-if="order.order_type==1" />

    </van-cell-group>

    <van-cell-group class="order_info" :border="false" inset v-if="!(order.order_status==6||order.order_status==7||order.order_status==10)">
      <van-cell title="订单号" :value="order.orderno" :border="false" />
      <van-cell title="下单时间" :value="order.order_time" :border="false" />
      <van-cell title="支付时间" :value="order.pay_time" :border="false" v-if="order.order_type==1" />

    </van-cell-group>
    <van-cell-group class="order_info" :border="false" inset v-if="(order.order_status==6||order.order_status==7||order.order_status==10)">
      <van-cell title="退款金额" :value="`￥${order.pay_amount}`" :border="false" />
      <van-cell title="退款编号" :value="order.orderno" :border="false" />
      <van-cell title="退款时间" :value="order.after_sales.update_time" :border="false" v-if="order.order_status==6" />

    </van-cell-group>
    <div class="reasonBox" v-if="(order.order_status==6||order.order_status==7||order.order_status==10)">
      <p>退款原因</p>
      <div class="reason">
        {{  order?.after_sales.content}}
      </div>
    </div>
    <div class="submit" v-if="order.order_status==1">
      <div class="price_info">
        <div class="settlement_total">
          <span class="num_total">共{{order.total}}件商品</span>
          <span class="pay_amount">合计:￥<span>{{order.pay_amount}}</span></span>
        </div>
        <div v-if="order.coupon_amount>0" class="coupon_amount">共减￥{{order.coupon_amount}}</div>
      </div>
      <van-button type="primary" round @click="onPayment">支付</van-button>
    </div>
  </div>
</template>

<script>
import { Dialog, Toast } from "vant";

export default {
  data () {
    return {
      order: {},
      product: [],
      status: {
        1: "待付款",
        2: "待发货",
        3: "待收货",
        4: "已完成",
        5: "已取消",
        6: "退款成功",
        7: "订单退货",
        10: "申请售后中"
      }, // 订单状态
      oid: "",
      address: {},
    };
  },
  created () {
    this.id = this.$route.query.id;
    this.getOrderDetail();
  },
  methods: {
    // 再次购买
    onAddCartClicked (list) {

      let arr = []
      list.forEach(ele => {
        this.$axios.post(this.$api.usereditcart, {
          product_id: ele.product_id, //商品id
          stock_id: ele.p_s_id,// 规格id
          quantity: ele.quantity,// 数量
        }).then(res => {
          const cart_id = res.data.data
          if (res.data.code == 1) {

            if (list.length - arr.length == 1) {
              arr.push(cart_id)

              this.$store.commit('setcart_id', arr.toString())
              setTimeout(() => {
                this.$router.push({ name: 'settlement' });
              }, 1000);
            } else {
              arr.push(cart_id)
            }



          } else {
            Toast.fail(res.data.msg)
          }

        })
      });


    },
    // 联系客服
    goCustomerService () {
      this.$router.push({ name: 'chat', query: { shop_id: this.product[0].shopinfo.shop_id } });
    },
    // 订单详情
    getOrderDetail () {
      this.$axios
        .get(this.$api.getorderdetail, {
          params: {
            order_id: this.id,
          },
        })
        .then((res) => {
          this.order = res.data.data.order;
          this.product = res.data.data.productinfo;
          //this.getAddress(this.order.address_id);

          this.order.order_time = this.$moment(
            Number(this.order.order_time) * 1000
          ).format("YYYY-MM-DD HH:mm:ss");
          this.order.pay_time = this.$moment(
            Number(this.order.pay_time) * 1000
          ).format("YYYY-MM-DD HH:mm:ss");
          this.order.update_time = this.$moment(
            Number(this.order.update_time) * 1000
          ).format("YYYY-MM-DD HH:mm:ss");
        });
    },

    // 复制运单号
    copyTrackingNumber () {
      let input = document.createElement("input"); // 创建input对象
      input.value = this.order.tracking_number; // 设置复制内容
      document.body.appendChild(input); // 添加临时实例
      input.select(); // 选择实例内容
      document.execCommand("Copy"); // 执行复制
      document.body.removeChild(input); // 删除临时实例
      Toast("复制成功");
    },
    // 支付
    onPayment () {
      this.$axios
        .post(this.$api.tobepaid, {
          order_id: this.id,
          pay_end: 1,
        })
        .then((res) => {
          if (res.data.code == 1) {
            this.StartWeiXinPay(res.data.data.data);
          } else {
            Toast.fail(res.data.msg);
          }
        });
    },
    // 调取微信支付
    StartWeiXinPay (pay_params) {
      if (typeof window.WeixinJSBridge === "undefined") {
        if (document.addEventListener) {
          document.addEventListener(
            "WeixinJSBridgeReady",
            this.onBridgeReady(pay_params),
            false
          );
          alert(1);
        } else if (document.attachEvent) {
          alert(2);
          document.attachEvent(
            "WeixinJSBridgeReady",
            this.onBridgeReady(pay_params)
          );
          document.attachEvent(
            "onWeixinJSBridgeReady",
            this.onBridgeReady(pay_params)
          );
        }
      } else {
        this.onBridgeReady(pay_params);
      }
    },
    onBridgeReady (pay_params) {
      var that = this;
      window.WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          appId: pay_params.appId, // 公众号名称，由商户传入
          timeStamp: pay_params.timeStamp, // 时间戳，自1970年以来的秒数
          nonceStr: pay_params.nonceStr, // 随机串
          package: pay_params.package, //统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
          signType: pay_params.signType, // 微信签名方式：
          paySign: pay_params.paySign, // 微信签名
        },
        function (res) {
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
            setTimeout(() => {
              that.$router.replace({
                name: "paymentSucess",
                query: { order_id: that.id },
              });
            }, 500);
          } else {
            Toast.fail("支付失败");
          }
        }
      );
    },
    // 取消订单
    cancelOrder () {
      Dialog.confirm({
        title: "提示",
        message: "确认取消订单？",
      })
        .then(() => {
          this.$axios
            .post(this.$api.usercancel, {
              order_id: this.id,
            })
            .then((res) => {
              if (res.data.code == 1) {
                Toast.success("已取消订单");
                setTimeout(() => {
                  this.getOrderDetail();
                }, 2000);
              } else {
                Toast.fail(res.data.msg);
              }
            });
        })
        .catch(() => {
          // on cancel
        });
    },
    // 提醒发货
    remindDelivery () {
      this.$axios
        .post(this.$api.userremind, {
          order_id: this.id,
        })
        .then((res) => {
          if (res.data.code == 1) {
            Toast.success("已提醒发货");
          } else {
            Toast.fail(res.data.msg);
          }
        });
    },
    // 确认收货
    confirmReceive () {
      Dialog.confirm({
        title: "提示",
        message: "确认收到了吗？",
        confirmButtonColor: "#FF4133",
      })
        .then(() => {
          this.$axios
            .post(this.$api.usersure, {
              order_id: this.id,
            })
            .then((res) => {
              if (res.data.code == 1) {
                Toast.success("已确认收货");
                setTimeout(() => {
                  this.getOrderDetail();
                }, 1500);
              } else {
                Toast.fail(res.data.msg);
              }
            });
        })
        .catch(() => {
          // on cancel
        });
    },
    // 店铺详情
    shopDetail (id) {
      this.$router.push({ name: "store", query: { id } });
    },
    //申请售后
    aftersale (id, did) {
      console.log(id, did);
      this.$router.push({ name: "addaftersale", query: { id, did } });
    },
    //查看物流
    logistics (id) {
      this.$router.push({ name: "logistics", query: { id } });
    },
    // 评价订单
    comments (o_id, d_id) {
      this.$router.push({
        name: "addComment",
        query: { type: "order", order_id: o_id, detail_id: d_id },
      });
    },
  },
};
</script>

<style scoped lang='less'>
.btn {
  color: #ff7733 !important;
  border: 1px solid #ff7733 !important;
}
.order-detail {
  min-height: calc(100vh - 60px);
  padding-bottom: 60px;
  /deep/.van-cell-group {
    border: 1px solid #f2f2f2;
    margin-bottom: 12px;
  }
  .order_status {
    .top_status {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 20px 0;
      .van-icon {
        font-size: 26px;
        margin-right: 10px;
      }
      .status {
        font-size: 16px;
        font-weight: bold;
      }
    }
  }
  .address {
    .address_detail {
      color: #201d1d;
      font-weight: bold;
    }
    .name {
      color: #757371;
      font-size: 14px;
      font-weight: normal;
      span:nth-child(1) {
        margin-right: 12px;
      }
    }
  }
  .logistics {
    .tracking_number {
      display: flex;
      align-items: center;
      color: #323233;
      font-size: 14px;
      margin-top: 10px;
      .van-icon {
        margin-left: 10px;
      }
    }
  }
  .products {
    .shopurl {
      .van-cell__left-icon {
        display: flex;
        align-items: center;
        width: 20px;
        height: 22px;
        margin-right: 8px;
      }
    }
    .product {
      margin-top: 0;
      background-color: #fff;
      /deep/.van-card__title {
        font-size: 14px;
      }
      /deep/ .van-card__price {
        font-size: 14px;
      }
    }
    .one_option_btn {
      display: flex;
      justify-content: flex-end;
      margin: 10px 0 6px;
      /deep/.van-button {
        width: 80px;
        margin-left: 10px;
      }
    }
    .option_btn {
      display: flex;
      justify-content: flex-end;
      padding: 6px 16px 12px;
      /deep/.van-button {
        width: 80px;
        margin-left: 10px;
      }
    }
  }
  .total {
    .not_showy {
      color: #06021a;
      font-size: 14px;
      font-weight: bold;
    }
    .showy {
      color: #fb2b2c;
      font-size: 14px;
      font-weight: bold;
    }
    .coupon_showy {
      color: #969799;
      font-size: 14px;
    }
  }
  .submit {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    padding: 5px 16px;
    border-radius: 16px 16px 0 0;
    background-color: #fff;
    box-sizing: border-box;
    .num_total {
      color: #bbb9b7;
      font-size: 12px;
      margin-left: 14px;
      margin-right: 8px;
    }
    .price_info {
      display: flex;
      flex-flow: column wrap;
      align-items: flex-end;
      margin-right: 16px;
      .settlement_total {
        font-size: 12px;
        .pay_amount span {
          color: #fb2b2c;
          font-size: 18px;
          font-weight: bold;
        }
      }
      .coupon_amount {
        color: #fb2b2c;
        font-size: 12px;
      }
    }
    .van-button {
      min-width: 102px;
    }
  }
}
.reasonBox {
  width: 343px;

  margin: 0 auto;
  background: #ffffff;
  border-radius: 10px;

  border: 1px solid #f2f2f2;
  padding: 12px 16px;
  box-sizing: border-box;
  p {
    font-size: 14px;
    color: rgba(4, 4, 4, 0.6);
  }
  .reason {
    font-size: 14px;
    color: rgba(32, 35, 39, 0.4);
    white-space: pre-wrap;
  }
}
</style>
